package com.aletto.general_store.ui.popup;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.model.AuctionGoods;
import com.aletto.general_store.presenters.core.SimpleTemplate;
import com.aletto.general_store.utils.XHelper;
import com.lxj.xpopup.core.BottomPopupView;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.ToastView;
import com.sisyphus.spinach.utils.watchers.EmptyRule;
import com.sisyphus.spinach.utils.watchers.OnWatcherCallback;
import com.sisyphus.spinach.utils.watchers.TextWatchers;

public class EditAuctionGoodsPopup extends BottomPopupView {

    public static int PRICE_TYPE = 1, NUMBER_TYPE = 2;

    private int type;
    private AuctionGoods item;

    private TextView tv_number;
    private EditText edit_number;
    private RadioGroup radio_group;


    public EditAuctionGoodsPopup(@NonNull Context context) {
        super(context);
    }

    public EditAuctionGoodsPopup(@NonNull Context context, AuctionGoods item, int type) {
        super(context);
        this.type = type;
        this.item = item;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.popup_edit_auction_goods;
    }

    @Override
    protected void onCreate() {
        super.onCreate();

        TextView tvTitle = findViewById(R.id.tv_title);
        View buttonSave = findViewById(R.id.button_save);
        findViewById(R.id.iv_close).setOnClickListener(v->dismiss());

        // 价格
        EditText edit_price = findViewById(R.id.edit_price);
//        edit_price.setText(XHelper.toPrice(Float.parseFloat(item.getPrice())));
        edit_price.setText(item.getPrice());
        edit_price.setSelection(edit_price.getText().length());

        // 库存
        edit_number = findViewById(R.id.edit_number);
        tv_number = findViewById(R.id.tv_number);
        radio_group = findViewById(R.id.radio_group);
        tv_number.setText(String.valueOf(item.getTotal_stock()));
        edit_number.addTextChangedListener(textWatcher);
        radio_group.setOnCheckedChangeListener((group, checkedId) -> initNumber(edit_number.getText()));

        if (type == PRICE_TYPE) {
            tvTitle.setText(R.string.edit_price);
            findViewById(R.id.layout_number).setVisibility(View.GONE);
            TextWatchers.add(new EmptyRule(edit_price)).setWatcherCallback(buttonSave::setEnabled);

        } else if (type == NUMBER_TYPE) {
            radio_group.check(R.id.radio_button_1);
            tvTitle.setText(R.string.edit_store_number);
            TextWatchers.add(new EmptyRule(edit_number)).setWatcherCallback(buttonSave::setEnabled);

            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                edit_price.clearFocus();
                edit_number.requestFocus();
            }, 500);

            findViewById(R.id.layout_price).setVisibility(View.GONE);
        }


        buttonSave.setOnClickListener(v -> {
            if (type == PRICE_TYPE) {
                updatePrice().execute();

            } else if (type == NUMBER_TYPE) {
                upGoodsStock().execute();
            }
        });
    }

    private void initNumber(CharSequence s) {

        if (TextUtils.isEmpty(s)) {
            return;
        }

        try {

            int parsed = Integer.parseInt(s.toString());

            if (radio_group.getCheckedRadioButtonId() == R.id.radio_button_2 && parsed > item.getTotal_stock()) {
                edit_number.getText().clear();
                tv_number.setText(String.valueOf(item.getTotal_stock()));
                return;
            }

            tv_number.setText(
                    String.valueOf(
                            item.getTotal_stock() + (radio_group.getCheckedRadioButtonId() == R.id.radio_button_1 ? parsed : -parsed)
                    )
            );

        } catch (NumberFormatException exception) {

            edit_number.setText(String.valueOf(Integer.MAX_VALUE));
            edit_number.setSelection(edit_number.getText().length());
            tv_number.setText(edit_number.getText());

        }
    }


    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            initNumber(s);
        }
    };

    private SimpleTemplate<Object> updatePrice() {
        return new SimpleTemplate<>() {
            @Override
            public INetTask.View<Object> view() {
                return new ToastView<>(getContext(), new INetTask.View<>() {
                    @Override
                    public void success(Object data) {
                        dismiss();
                    }
                });
            }

            @Override
            public INetTask.Presenter<Object, INetTask.View<Object>> presenter() {
                EditText edit_price = findViewById(R.id.edit_price);
                float price = Float.parseFloat(edit_price.getText().toString());
                return new NetSingleTask<>(DataRepository.getInstance().upGoodsPrice(item.getId(), price));
            }
        };
    }

    private SimpleTemplate<Object> upGoodsStock() {
        return new SimpleTemplate<>() {
            @Override
            public INetTask.View<Object> view() {
                return new ToastView<>(getContext()){
                    @Override
                    public void success(Object data) {
                        dismiss();
                    }
                };
            }

            @Override
            public INetTask.Presenter<Object, INetTask.View<Object>> presenter() {
                int type = radio_group.getCheckedRadioButtonId() == R.id.radio_button_1 ? 1 : 2;
                int number = Integer.parseInt(edit_number.getText().toString());
                return new NetSingleTask<>(DataRepository.getInstance().upGoodsStock(item.getId(), type, number));
            }
        };
    }
}
